package com.easy.admin.system.websocket;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.springframework.stereotype.Component;

import javax.websocket.OnClose;
import javax.websocket.OnMessage;
import javax.websocket.OnOpen;
import javax.websocket.Session;
import javax.websocket.server.PathParam;
import javax.websocket.server.ServerEndpoint;
import java.util.concurrent.CopyOnWriteArrayList;
import java.util.concurrent.CopyOnWriteArraySet;

/**
 * websocket 服务
 */
@ServerEndpoint("/websocket/{sid}")
@Component
public class WebSocketServer {
    private static Log log = LogFactory.getLog(WebSocketServer.class);
    private static  int onLineConut=0;//记录当前在线人数
    //线程安全的集合，用来存放每一个客户端的Server
    private static CopyOnWriteArraySet<WebSocketServer> copyOnWriteArraySet = new CopyOnWriteArraySet();
    private  Session session ;

    private String sid;//当前会话的id

    @OnOpen
    public void onOpen(Session session, @PathParam("sid")String sid){
        this.session = session;
        this.sid = sid;
        copyOnWriteArraySet.add(this);//加入当前对象到集合中
        log.info("有新的用户上线》》》》》》"+onLineConut);
        log.info("id"+sid);
        onLineConut++;//在线人数+1;
    }

    @OnClose
    public void onClose(){
        copyOnWriteArraySet.remove(this);
        onLineConut--;
        log.info("有用户退出。。。"+onLineConut);
    }

    @OnMessage
    public void onMessage(String message,Session session){
        log.info("收到消息："+this.sid+":::"+message);
        //群发消息
        for(WebSocketServer item: copyOnWriteArraySet){
            item.sendMessage(message);
        }
    }

    /**
     * 服务器主动发送消息
     */
    public  void sendMessage(String message){
        message = String.valueOf(onLineConut);
        try{
            for(WebSocketServer server:copyOnWriteArraySet) {
                server.session.getBasicRemote().sendText(message);
            }
            log.info("推送消息成功》》" + message);
        }catch (Exception e){
            e.printStackTrace();
            log.info("推送消息出现错误》》》》");
        }

    }

}
